package com.runfast.waimai.web.controller;

import com.runfast.common.utils.TokenUtil;
import com.runfast.common.web.entity.Result;
import com.runfast.common.web.entity.ResultCode;
import com.runfast.waimai.common.Constants;
import com.runfast.waimai.entity.Cart;
import com.runfast.waimai.service.RunfastActivityService;
import com.runfast.waimai.service.RunfastBusinessService;
import com.runfast.waimai.service.RunfastGoodsSellRecordService;
import com.runfast.waimai.service.RunfastRedPacketRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 红包接口
 */
@RestController("userWmRedPacketController")
@RequestMapping(value = "/api/user/wm/redPacket", headers = "token")
public class RedPacketController {

    @Autowired
    private RunfastActivityService activityService;

    @Autowired
    private RunfastRedPacketRecordService redPacketRecordService;

    @Autowired
    private RunfastGoodsSellRecordService orderService;

    @Autowired
    private RunfastBusinessService businessService;


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取用户通用红包活动分页列表
     *
     * @param token
     * @return
     */
    @PostMapping("/listRed")
    public Result listRed(@PageableDefault Pageable pageable, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);

        List<Integer> activityTypeList = new ArrayList<>();
        activityTypeList.add(12);
        List<Map<String, Object>> redPacketRecordList = redPacketRecordService.findRedRecord(userId, activityTypeList, pageable);
        Date now = new Date();
        for (Map<String, Object> map : redPacketRecordList) {
            /*Date endTime = (Date) map.get("endTime");
            if(endTime.after(now)) map.put("expired", false);
            else map.put("expired", true);*/
            map.put("businessName", null);
        }


        return Result.ok("", redPacketRecordList);
    }

    /**
     * 获取用户商家代金券活动分页列表
     *
     * @param pageable
     * @param token
     * @return
     */
    @PostMapping("/listCoupon")
    public Result listCoupon(@PageableDefault Pageable pageable, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);

        List<Integer> activityTypeList = new ArrayList<>();
        activityTypeList.add(10);
        activityTypeList.add(11);
        List<Map<String, Object>> redPacketRecordList = redPacketRecordService.findRedRecord(userId, activityTypeList, pageable);

        Date now = new Date();
        for (Map<String, Object> map : redPacketRecordList) {
            /*Date endTime = (Date) map.get("endTime");
            if(endTime.after(now)) map.put("expired", false);
            else map.put("expired", true);*/
            Integer activityType = (Integer) map.get("activityType");
            Integer businessId = (Integer) map.get("businessId");

            Map<String, Object> businessMap = businessService.findNameById(businessId);

            String name = (String) businessMap.get("name");
            map.put("businessName", name);
        }


        return Result.ok("", redPacketRecordList);
    }


    /**
     * 获取下单时可用的红包活动
     *
     * @param businessId 订单id
     * @param token
     * @return
     */
    @PostMapping("/listValid")
    public Result listValid(@RequestParam Integer businessId, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);
        HashOperations hashOperations = redisTemplate.opsForHash();
        Cart redisCart = (Cart) hashOperations.get(Constants.REDIS_NAMESPACE_CART + userId, businessId);
        if (redisCart == null) return Result.fail(ResultCode.FAIL, "购物车为空，请先添加购物车");

        /**
         * 获取用户当前有效的红包
         */
        List<Integer> activityTypeList = new ArrayList<>();
        activityTypeList.add(12);

        List<Map<String, Object>> redPacketRecordList = redPacketRecordService.findValidRedRecord(userId, businessId, null, activityTypeList);
//        List<Map<String, Object>> redPacketRecordList = redPacketRecordService.findRedRecord(userId, activityTypeList, null);

        for (Map<String, Object> map : redPacketRecordList) {
            Double full = (Double) map.get("full");
            Integer isBigThan = redisCart.getTotalPay().compareTo( BigDecimal.valueOf(full) );
            if(isBigThan==-1)
                map.put("possibleUse", false);
            else
                map.put("possibleUse", true);

            Integer bId = (Integer) map.get("businessId");
            Map<String, Object> businessMap = businessService.findNameById(bId);
            String name = (String) businessMap.get("name");

            map.put("businessName", name);
        }
        return Result.ok("", redPacketRecordList);
    }


    @PostMapping("/listValidCoupon")
    public Result listValidCoupon(@RequestParam Integer businessId, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);
        HashOperations hashOperations = redisTemplate.opsForHash();
        Cart redisCart = (Cart) hashOperations.get(Constants.REDIS_NAMESPACE_CART + userId, businessId);
        if (redisCart == null) return Result.fail(ResultCode.FAIL, "购物车为空，请先添加购物车");


        /**
         * 获取用户当前有效的红包
         */
        List<Integer> activityTypeList = new ArrayList<>();
        activityTypeList.add(10);
        activityTypeList.add(11);

        List<Map<String, Object>> redPacketRecordList = redPacketRecordService.findValidRedRecord(userId, businessId, null, activityTypeList);
//        List<Map<String, Object>> redPacketRecordList = redPacketRecordService.findRedRecord(userId, activityTypeList, null);

        for (Map<String, Object> map : redPacketRecordList) {

            Integer isBigThan = redisCart.getTotalPay().compareTo( BigDecimal.valueOf((Double) map.get("full")) );
            if(isBigThan==-1)
                map.put("possibleUse", false);
            else
                map.put("possibleUse", true);

            Integer activityType = (Integer) map.get("activityType");
            Integer bId = (Integer) map.get("businessId");

            Map<String, Object> businessMap = businessService.findNameById(bId);

            String name = (String) businessMap.get("name");
            map.put("businessName", name);
        }

        return Result.ok("", redPacketRecordList);
    }


    /**
     * 领取红包
     *
     * @param redActivityId 红包活动id
     * @param token
     * @return
     */
    @PostMapping("/pick")
    public Result get(@RequestParam Integer redActivityId, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);

        return activityService.pick(redActivityId, userId);


    }


    /**
     * 通用红包可用数量
     *
     * @param token
     * @return
     */
    @PostMapping("/redCount")
    public Result redCount(@RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);
        List<Integer> activityTypeList = new ArrayList<>();
        activityTypeList.add(12);
        long count = redPacketRecordService.redCount(userId, activityTypeList);
        return Result.ok("", count);


    }

    /**
     * 商家优惠券可用数量
     *
     * @param token
     * @return
     */
    @PostMapping("/couponCount")
    public Result couponCount(@RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);
        List<Integer> activityTypeList = new ArrayList<>();
        activityTypeList.add(10);
        activityTypeList.add(11);
        long count = redPacketRecordService.redCount(userId, activityTypeList);
        return Result.ok("", count);


    }


}
